package com.xjm.i1.core.generator.Conveter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.lang.reflect.Field;

/**
 * @deprecated
 * ExcelProperty中自定义转换器，用于转换enum 与 String写入写出
* */
public class ExcelEnumStringConverter implements Converter<Enum> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return Enum.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Enum convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String stringValue = cellData.getStringValue();
        if (StrUtil.isEmpty(stringValue)) {
            return null;
        }
        Class<?> type = contentProperty.getField().getType();
        if (type.isAssignableFrom(Enum.class)) {
            Enum e = (Enum) type.newInstance();
            Field val = type.getDeclaredField("val");
            val.setAccessible(true);
            val.set(e, type);
            return e;
        }
        return null;
    }

    @Override
    public WriteCellData<?> convertToExcelData(Enum value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return Converter.super.convertToExcelData(value, contentProperty, globalConfiguration);
    }
}
